/*
*Copyright 2021-2023 NERCIS
*
*Licensed under the Apache License, Version 2.0 (the "License");
*you may not use this file except in compliance with the License.
*You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
*Unless required by applicable law or agreed to in writing, software
*distributed under the License is distributed on an "AS IS" BASIS,
*WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*See the License for the specific language governing permissions and
*limitations under the License.
*/

package cn.ac.nercis.pes.community.controller.evaluation.prepare.asset;

import cn.ac.nercis.pes.common.constant.common.AssetConstants;
import cn.ac.nercis.pes.common.constant.evaluation.EvaluationModule;
import cn.ac.nercis.pes.common.constant.project.FinishState;
import cn.ac.nercis.pes.common.constant.project.SystemState;
import cn.ac.nercis.pes.community.component.dialog.*;
import cn.ac.nercis.pes.community.controller.base.GlobalEventHandle;
import cn.ac.nercis.pes.community.controller.base.InitEvalDataLoad;
import cn.ac.nercis.pes.community.controller.evaluation.prepare.PrepareController;
import cn.ac.nercis.pes.community.model.vo.asset.BaseAssetVO;
import cn.ac.nercis.pes.community.utils.AppStore;
import cn.ac.nercis.pes.community.utils.IconUtils;
import cn.ac.nercis.pes.community.utils.LogUtils;
import cn.ac.nercis.pes.community.views.evaluation.prepare.PrepareView;
import cn.ac.nercis.pes.model.dto.project.SystemProcessDTO;
import cn.ac.nercis.pes.service.evaluation.AssetService;
import cn.ac.nercis.pes.service.project.SystemProcessService;
import javafx.application.Platform;
import javafx.beans.property.SimpleBooleanProperty;
import javafx.scene.control.Button;
import javafx.scene.layout.StackPane;
import lombok.extern.slf4j.Slf4j;

import java.util.Set;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutorService;

/**
 * 基础系统资产管理控制器
 * @author zpy
 * @version 1.0.0
 */
@Slf4j
public abstract class BaseAssetController implements GlobalEventHandle, InitEvalDataLoad {


    protected final SimpleBooleanProperty dataSaving = new SimpleBooleanProperty(false);

    protected void initAssetDefaultValue(BaseAssetVO assetVO){
        assetVO.setIsUse(AssetConstants.USE_TAG);
    }

    protected void initButtonIcons(Button searchButton, Button saveButton, Button tmpSaveButton) {
        searchButton.setGraphic(IconUtils.getGlyph("search-icon", "btn-icon"));
        saveButton.setGraphic(IconUtils.getGlyph("save-button-icon", "btn-icon"));
        tmpSaveButton.setGraphic(IconUtils.getGlyph("temp-save-button-icon", "btn-icon"));

    }

    protected void initSaveListener(Button saveButton, Button tmpSaveButton){
        saveButton.disableProperty().bind(dataSaving);
        tmpSaveButton.disableProperty().bind(dataSaving);
    }

    protected void checkDeleteAsset(final Set<String> ids) {
        dataSaving.setValue(true);
        LogUtils.info(log, "执行资产对象删除前检查...");
        LogUtils.record(log, "请求数据，systemId:{}，assetIds：{}", this.getCurrentSystemId(), ids);
        CompletableFuture.supplyAsync(() -> this.getAssetService().batchCheckAssetEvalRecord(this.getCurrentSystemId(), ids),getExecutorService())
                .thenAccept(res -> Platform.runLater(() -> {
                    dataSaving.setValue(false);
                    if (res.isSuccess()) {
                        deleteAsset(ids);
                    } else {
                        AlertDialog alertDialog = AlertDialog.builder()
                                .withMode(AlertMode.CONFIRM)
                                .withType(AlertType.WARN)
                                .withTitle("操作提示")
                                .withContent(res.getMsg())
                                .withContainer(this.getPage())
                                .build();
                        alertDialog.show((confirm) -> {
                            if (confirm) {
                                deleteAsset(ids);
                            }
                        });
                    }
                }))
                .exceptionally((ex) -> {
                    dataSaving.setValue(false);
                    log.error("执行资产对象删除前检查出错!", ex);
                    return null;
                });
    }

    protected void deleteAsset(final Set<String> assetIds) {
        dataSaving.setValue(true);
        LogUtils.info(log, "删除资产对象信息...");
        LogUtils.info(log, "请求数据：{}", assetIds);
        CompletableFuture.supplyAsync(() -> this.getAssetService().batchDeleteAsset(assetIds),getExecutorService())
                .thenAccept(res -> Platform.runLater(() -> {
                    dataSaving.setValue(false);
                    if (res.isSuccess()) {
                        //更新表数据
                        this.queryAsset();
                        MessageDialog.builder()
                                .withContainer(this.getPage())
                                .withType(MessageType.SUCCESS).withMessage("删除成功")
                                .build().show();
                        refreshFinishProcess(false);
                    } else {
                        MessageDialog.builder()
                                .withContainer(this.getPage())
                                .withType(MessageType.FAIL).withMessage(res.getMsg())
                                .build().show();
                    }
                }))
                .exceptionally((ex) -> {
                    dataSaving.setValue(false);
                    log.error("删除资产对象信息出错!", ex);
                    return null;
                });
    }



    protected void setSystemProcess(EvaluationModule menu, FinishState state){
        var process = SystemProcessDTO.builder()
                .systemId(this.getCurrentSystemId())
                .state(SystemState.PREPARE)
                .name(menu.getName())
                .finishState(state)
                .build();
        LogUtils.info(log,"保存资产测评进度：{}",process);
        CompletableFuture.supplyAsync(() -> getProcessService().setSystemProcess(process),getExecutorService())
                .thenAccept(res -> Platform.runLater(() -> {
                    if (!res.isSuccess()) {
                        MessageDialog.builder()
                                .withType(MessageType.WARN)
                                .withMessage("记录测评进度失败")
                                .withContainer(getPage())
                                .build().show();
                    }else{
                        var prepareView = AppStore.getEvaluationView(this.getCurrentSystemId(), PrepareView.class);
                        if(prepareView.getController() instanceof PrepareController controller){
                            controller.refreshEvalProcess();
                        }
                    }
                }))
                .exceptionally((ex) -> {
                    log.error("保存系统测评进度出错!", ex);
                    return null;
                });
    }

    protected abstract StackPane getPage();
    protected abstract String getCurrentSystemId();
    protected abstract void onSuccessImport();
    protected abstract AssetService getAssetService();
    protected abstract SystemProcessService getProcessService();
    protected abstract ExecutorService getExecutorService();
    protected abstract void queryAsset();
    protected abstract void refreshFinishProcess(boolean finish);
}